package com.lyl.momanapp.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.PreviewCallback;
import android.media.FaceDetector;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.lyl.momanapp.R;
import com.lyl.momanapp.bean.URL;
import com.lyl.momanapp.util.utlis.MyUtils;
import com.lyl.momanapp.util.view.FindFaceView;
import com.lyl.momanapp.util.view.MyBaseActivity;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 名字 梁亚龙
 * 时间 2017/10/18.
 * QQ邮箱 503934353@qq.com
 */

public class FaceActivity extends MyBaseActivity {
    private SurfaceView preview;
    private Camera camera;
    private Camera.Parameters parameters;
    private int orientionOfCamera;// 前置摄像头的安装角度
    private int faceNumber;// 识别的人脸数
    private FaceDetector.Face[] faces;
    private FindFaceView mFindFaceView;
    private int cameranum = 0;
    private Button bt_camera;
    private int cameraPosition = 1;//0代表前置摄像头，1代表后置摄像头
    private SurfaceHolder mHolder;
    private static final String IMAGE_UNSPECIFIED = "image/*";
    private final int IMAGE_CODE = 0; // 这里的IMAGE_CODE是自己任意定义的
    @Override
    public void initUI() {
        setContentView(R.layout.activity_face);

        bt_camera = (Button) findViewById(R.id.bt_camera);
        bt_camera.setOnClickListener(this);

        mFindFaceView = (FindFaceView) findViewById(R.id.my_preview);
        ((ImageView) findViewById(R.id.iv_photo)).setOnClickListener(this);
        preview = (SurfaceView) findViewById(R.id.preview);
        findViewById(R.id.face_change).setOnClickListener(this);
        findViewById(R.id.face_back).setOnClickListener(this);
        // 设置缓冲类型
        preview.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        // 设置surface的分辨率
        preview.getHolder().setFixedSize(176, 144);
        // 设置屏幕常亮
        preview.getHolder().setKeepScreenOn(true);
        preview.getHolder().addCallback(new SurfaceCallback());
    }


    @Override
    public void initData() {

    }

    @Override
    public void addListeners() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_camera:
                if (camera != null) {
                    try {
                        camera.takePicture(null, null, new MyPictureCallback());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.face_change: {
                if (cameraPosition == 0) {
                    cameraPosition = 1;
                    preview.getHolder().addCallback(new SurfaceCallback());
                } else {
                    cameraPosition = 0;
                    preview.getHolder().addCallback(new SurfaceCallback());
                }
            }
            break;
            case R.id.face_back: {
                URL.RESULT_OK = 2;
                startActivity(new Intent(FaceActivity.this, TwoActivity.class));
            }
            break;
            case R.id.iv_photo: {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
                startActivityForResult(intent, IMAGE_CODE);
            }
            break;
        }
    }

    private final class MyPictureCallback implements PictureCallback {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            try {
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
                        data.length);
                Matrix matrix = new Matrix();
                matrix.setRotate(-90);
                Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap
                        .getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                //                iv_photo.setImageBitmap(bmp);  图片预览
                URL.imgURL = new MyUtils().saveBitmap(bmp, new MyUtils().getTime(), FaceActivity.this);
                URL.RESULT_OK = 1;
                saveFile(bmp,"asdasd.jpg");
                startActivity(new Intent(FaceActivity.this, TwoActivity.class));

                camera.startPreview();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 设置相机的显示方向（这里必须这么设置，不然检测不到人脸）
     *
     * @param cameraId 相机ID(0是后置摄像头，1是前置摄像头）
     * @param camera   相机对象
     */
    private void setCameraDisplayOrientation(int cameraId, Camera camera) {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId, info);
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        int degree = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degree = 0;
                break;
            case Surface.ROTATION_90:
                degree = 90;
                break;
            case Surface.ROTATION_180:
                degree = 180;
                break;
            case Surface.ROTATION_270:
                degree = 270;
                break;
        }

        orientionOfCamera = info.orientation;
        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degree) % 360;
            result = (360 - result) % 360;
        } else {
            result = (info.orientation - degree + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }

    private void detectionFaces(byte[] data) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        Bitmap bitmap1 = BitmapFactory.decodeByteArray(data, 0, data.length,
                options);
        int width = bitmap1.getWidth();
        int height = bitmap1.getHeight();
        Matrix matrix = new Matrix();
        Bitmap bitmap2 = null;
        FaceDetector detector = null;
        switch (orientionOfCamera) {
            case 0:
                detector = new FaceDetector(width, height, 1);
                matrix.postRotate(0.0f, width / 2, height / 2);
                // 以指定的宽度和高度创建一张可变的bitmap（图片格式必须是RGB_565，不然检测不到人脸）
                bitmap2 = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
                break;
            case 90:
                detector = new FaceDetector(height, width, 1);
                matrix.postRotate(-270.0f, height / 2, width / 2);
                bitmap2 = Bitmap.createBitmap(height, width, Bitmap.Config.RGB_565);
                break;
            case 180:
                detector = new FaceDetector(width, height, 1);
                matrix.postRotate(-180.0f, width / 2, height / 2);
                bitmap2 = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
                break;
            case 270:
                detector = new FaceDetector(height, width, 1);
                matrix.postRotate(-90.0f, height / 2, width / 2);
                bitmap2 = Bitmap.createBitmap(height, width, Bitmap.Config.RGB_565);
                break;
        }

        faces = new FaceDetector.Face[1];
        Paint paint = new Paint();
        paint.setDither(true);
        Canvas canvas = new Canvas();
        canvas.setBitmap(bitmap2);
        canvas.setMatrix(matrix);
        // 将bitmap1画到bitmap2上（这里的偏移参数根据实际情况可能要修改）
        canvas.drawBitmap(bitmap1, -40.0F, 40.0F, paint);
        faceNumber = detector.findFaces(bitmap2, faces);
        Log.e("检测到人脸数", faceNumber + "");


        if (faceNumber != 0) {
            MyUtils.showToast(FaceActivity.this, "别动", Toast.LENGTH_SHORT);
            mFindFaceView.setVisibility(View.VISIBLE);
            mFindFaceView.drawRect(faces, faceNumber);
        } else {
            MyUtils.showToast(FaceActivity.this, "人脸呢", Toast.LENGTH_SHORT);
            mFindFaceView.setVisibility(View.GONE);
        }
        bitmap2.recycle();
        bitmap1.recycle();
    }

    private final class SurfaceCallback implements SurfaceHolder.Callback {

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
            if (camera != null) {
                parameters = camera.getParameters();
                parameters.setPictureFormat(PixelFormat.JPEG);
                // 设置预览区域的大小
                parameters.setPreviewSize(width, height);
                // 设置每秒钟预览帧数
                parameters.setPreviewFrameRate(5);
                // 设置预览图片的大小
                parameters.setPictureSize(width, height);
                parameters.setJpegQuality(80);
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            int cameraCount = 0;
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            cameraCount = Camera.getNumberOfCameras();
            mHolder = holder;// SurfaceHolder是系统提供用来设置surfaceView的对象
            for (int i = 0; i < cameraCount; i++) {
                Camera.getCameraInfo(i, cameraInfo);
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    try {
                        camera = Camera.open(cameraPosition);
                        camera.setPreviewDisplay(holder);
                        setCameraDisplayOrientation(cameraPosition, camera);
                        camera.setPreviewCallback(new MyPreviewCallback());
                        camera.startPreview();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            if (camera != null) {
                camera.setPreviewCallback(null);
                camera.stopPreview();
                camera.release();
                camera = null;
            }
        }

    }

    private class MyPreviewCallback implements PreviewCallback {

        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
            Camera.Size size = camera.getParameters().getPreviewSize();
            YuvImage yuvImage = new YuvImage(data, ImageFormat.NV21,
                    size.width, size.height, null);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            yuvImage.compressToJpeg(new Rect(0, 0, size.width, size.height),
                    80, baos);
            byte[] byteArray = baos.toByteArray();
            detectionFaces(byteArray);
        }

    }



    public void saveFile(Bitmap bm, String fileName) throws IOException {
        String path = Environment.getExternalStorageDirectory() + File.separator;
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub


        Bitmap bm = null;

        // 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口

        ContentResolver resolver = getContentResolver();

        if (requestCode == IMAGE_CODE) {

            try {

                Uri originalUri = data.getData(); // 获得图片的uri

                bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);


                String[] proj = { MediaStore.Images.Media.DATA };

                // 好像是android多媒体数据库的封装接口，具体的看Android文档
                Cursor cursor = managedQuery(originalUri, proj, null, null, null);

                // 按我个人理解 这个是获得用户选择的图片的索引值
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                // 将光标移至开头 ，这个很重要，不小心很容易引起越界
                cursor.moveToFirst();
                // 最后根据索引值获取图片路径
                String path = cursor.getString(column_index);
                URL.imgURL = path;
                URL.RESULT_OK = 1;
                saveFile(bm,"asdasd.jpg");
                startActivity(new Intent(FaceActivity.this, TwoActivity.class));
            } catch (IOException e) {
                Log.e("TAG-->Error", e.toString());

            }

            finally {
                return;
            }
        }

        super.onActivityResult(requestCode, resultCode, data);

    }
}